<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/5/11
 * Time: 11:29
 */

namespace app\api\traits;

use EasyWeChat\Foundation\Application;

trait Wechat
{
//微信平台
    protected static $options = [
        /**
         * Debug 模式，bool 值：true/false
         *
         * 当值为 false 时，所有的日志都不会记录
         */
        'debug' => false,
        /**
         * 账号基本信息，请从微信公众平台/开放平台获取
         */
        'app_id' => '',
        'secret' => '',
        'token' => '',
        'aes_key' => '',
        'we_name' => '',
        'we_id' => '',
        'we_number' => '',
        'we_type' => 1,
        /**
         * 日志配置
         *
         * level: 日志级别, 可选为：
         *         debug/info/notice/warning/error/critical/alert/emergency
         * permission：日志文件权限(可选)，默认为null（若为null值,monolog会取0644）
         * file：日志文件位置(绝对路径!!!)，要求可写权限
         */
        'log' => [
            'level' => 'debug',
            'permission' => 0777,
            'file' => '../runtime/log/easywechatzjs.log',
        ],
        /**
         * OAuth 配置
         *
         * scopes：公众平台（snsapi_userinfo / snsapi_base），开放平台：snsapi_login
         * callback：OAuth授权完成后的回调页地址
         */
        'oauth' => [
            'scopes' => ['snsapi_userinfo'],
            'callback' => 'api/receive/olist.html',
        ],
        /**
         * 微信支付
         */
        'payment' => [
            'merchant_id' => '',
            'key' => '',
            'cert_path' => '', // XXX: 绝对路径！！！！
            'key_path' => '',      // XXX: 绝对路径！！！！
            'sandbox_mode'=>false,
            // 'device_info'     => '013467007045764',
            // 'sub_app_id'      => '',
            // 'sub_merchant_id' => '',
            // ...
        ],
        /**
         * Guzzle 全局设置
         *
         * 更多请参考： http://docs.guzzlephp.org/en/latest/request-options.html
         */
        'guzzle' => [
            'timeout' => 300.0, // 超时时间（秒）
            'verify' => false, // 关掉 SSL 认证（强烈不建议！！！）
        ],
    ];
    public static $app = null;

    /**
     * 静态方法，单例统一访问入口
     * @return Application|null
     */
    static public function getInstance()
    {

        if (is_null(self::$app)) {
            $config = config('we_options');

            if (!empty($config)) {
//                $config['oauth']['scopes'] = ['snsapi_userinfo'];
//                $config['oauth']['callback'] = url('zjs/receive/index', '', TRUE, TRUE);
                self::$options = array_merge(self::$options, $config);
            }
            self::$app = new Application(self::$options);
//            $token = get_access_token();
//            self::$app['access_token']->setToken($token);  // 单位：秒
        }
        return self::$app;
    }
    public function traceHttp($str)
    {
        $this->logger($str);
//        $this->logger("\n\nREMOTE_ADDR:" . $_SERVER["REMOTE_ADDR"] . (strstr($_SERVER["REMOTE_ADDR"], '101.226') ? " FROM WeiXin" : "Unknown IP"));
//        $this->logger("QUERY_STRING:" . $_SERVER["QUERY_STRING"]);
    }

    function logger($log_content=null)
    {
        $max_size = 500000;
        $log_filename = "log.html";
        if (file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)) {
            unlink($log_filename);
        }
        file_put_contents($log_filename, date('Y-m-d H:i:s'). $log_content."\r\n", FILE_APPEND);
    }
    /**
     * 检测微信是否为检测请求 并进行加密认证
     * @return bool
     */
    private function checkSignature()
    {
        $signature =input('signature');
        $timestamp = input('timestamp');
        halt($signature);
        $nonce = input('nonce');
        $config=config('we_options');
        if(!empty($config)) self::$options=array_merge(self::$options,$config);
        $token = self::$options['token'];
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }

    /**发送微信模板消息
     * @param $data
     * @return bool
     */
    public function sendWechat($data){
        $wechattype = new WechatTypeZjs();
        $wechatmessage = new WechatZjsMessage($wechattype,$data);
        $wesmslog = new Wesmslog();
        $str = '';
        foreach ($data as $key=>$v){
            $str.=$key.":".$v.';';
        }
        $arr['send_id']     = $data['sendid'];
        $arr['receive_id']  = $data['userid'];
        $arr['order_id']    = $data['orderid'];
        $arr['send_msg']    = $str;
        $arr['log_type']    = 3;
        $array=false;
        try{
            $array = $wechatmessage->sendMessage();
        }catch (\Exception $exception){
            $arr['is_success']  = 2;
            $arr['error_msg']   ='用户id为'.$data['userid'].'的微信推送失败！错误信息是:'.$exception->getMessage().'，错误代码是:'.$exception->getCode();;
        }
        $wesmslog->save($arr);
        return $array;
    }

    /**
     * 获取accesstoken
     * @return string
     */
    public function getaccesstoken($qiangzhi)
    {
        return self::getInstance()->access_token->getToken($qiangzhi);
    }
}